package ru.housewifes.common;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.cfg.Environment;
import org.hibernate.dialect.PostgreSQLDialect;
import org.junit.After;
import ru.common.hibernate.HibernateAction;
import ru.common.hibernate.HibernateActionExecutor;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * TODO: add description
 *
 * @author Alexander Troshanin
 */
public class HibernateTestSupport {

    private static final String CONFIG_LOCATION = "/ru/housewife/model/hibernate.cfg.xml";

    private final Connection connection;

    private final Session session;

    public HibernateTestSupport() {
        try {
            Class.forName("org.postgresql.Driver");
            connection = DriverManager.getConnection("jdbc:postgresql://localhost/housewifes", "postgres", "postgres");
        } catch (Exception e) {
            throw new IllegalStateException(e);
        }
        AnnotationConfiguration cfg = new AnnotationConfiguration();
        cfg.configure(HibernateTestSupport.class.getResource(CONFIG_LOCATION));
        cfg.getProperties().setProperty(Environment.DIALECT, PostgreSQLDialect.class.getName());
        cfg.getProperties().setProperty(Environment.SHOW_SQL, "true");

        SessionFactory f = cfg.buildSessionFactory();
        session = f.openSession(connection);
    }

    public Session getSession() {
        return session;
    }

    public HibernateActionExecutor getExecutor() {
        return new HibernateActionExecutor() {

            @Override
            public <T> T execute(HibernateAction<T> callback) {
                return callback.execute(getSession());
            }

            @Override
            public <T> T executeSeparately(HibernateAction<T> action) {
                return execute(action);
            }

        };
    }

    @After
    public void release() throws SQLException {
        session.close();
        connection.close();
    }

}
